// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'
import Client from '@api/elemac/api/BaDeviceApiControllerApi'
import OneClass from '@api/elemac/model/BaDeviceDetailReq'
import InfoClass from '@api/elemac/model/BaDeviceCurveReq'
import SubmitClass from '@api/elemac/model/BaDeviceControlReq'

const CLIENT = CORE.grpcCLIENT(Client)

// ============================== 导出远程接口 ============================== //

export default {
  // —————————————————————————————— 单项 —————————————————————————————— //

  async getOne({ id }, TIP = '查询详情') {
    const DTO = CORE.grpcDTO(OneClass, { deviceId: id })
    const resp = await CORE.grpc(TIP, CLIENT, 'baDeviceDetail', DTO)
    return resp || {}
  },
  transOne({ baDeviceDto = {}, messageAlarmDto = {} }) {
    const { deviceDto = {}, baDevicePropertyDtos: propList = [], yxzt, gzzt, sbqt } = baDeviceDto
    if (!CORE.isEmpty(messageAlarmDto)) {
      const { id, alarmTime: time, alarmDetail: name } = messageAlarmDto
      deviceDto.alarmId = id
      deviceDto.alarmContent = `${CORE.timeStr(time)} 产生${name}`.replace(/((告|报)警)?$/, CORE.MAP.ALARM)
    }
    if (!CORE.isEmpty(yxzt)) deviceDto.yxztValue = yxzt.value
    if (!CORE.isEmpty(gzzt)) deviceDto.gzztValue = gzzt.value
    if (!CORE.isEmpty(sbqt)) deviceDto.sbqtValue = sbqt.value
    propList.forEach((prop) => (deviceDto[`${prop.code}Value`] = prop.value))
    return { ...deviceDto, deviceId: deviceDto.id, yxzt, gzzt, sbqt, propList }
  },

  // —————————————————————————————— 信息 —————————————————————————————— //

  validInfoParam(infoParam) {
    return infoParam.deviceId && infoParam.code
  },
  async getInfo(infoParam, TIP = '查询信息') {
    const DTO = CORE.grpcDTO(InfoClass, infoParam)
    const resp = await CORE.grpc(TIP, CLIENT, 'baDeviceCurve', DTO)
    return resp.curveMap || {}
  },
  transInfo(obj, { state: { infoParam: { startTime } } }) {
    const dataList = Array(25).fill(0)
    Object.keys(obj).forEach((time) => {
      if ((time - startTime) % 3600000) return // 非整点的忽略
      const index = (time - startTime) / 3600000
      dataList[index] += obj[time]
    })
    return { dataList }
  },

  // —————————————————————————————— 提交 —————————————————————————————— //

  async submit(one, TIP = '提交') {
    const DTO = CORE.grpcDTO(SubmitClass, one)
    await CORE.grpc(TIP, CLIENT, 'baDeviceControl', DTO)
    return CORE.grpcOK(TIP)
  },
}
